package org.capgemini.tienda.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.capgemini.tienda.utils.RequestKeys;
import org.capgemini.tienda.utils.SessionKeys;
import org.capgemini.tienda.vo.UsuarioVO;


public class FiltroAdministrador implements Filter{

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		final HttpSession session=((HttpServletRequest) request).getSession();
		

			synchronized (session) {
				UsuarioVO usuario=(UsuarioVO) session.getAttribute(SessionKeys.USUARIO);
				if(!usuario.getRole().equals("administrador")){
					request.setAttribute(RequestKeys.ERROR, "Debe ser administrador para acceder a la pagina solicitada");
					RequestDispatcher rd = request.getRequestDispatcher("/inicio.do");
					
					if(usuario.getRole().equals("cliente")) rd=request.getRequestDispatcher("/panel.do");
					rd.forward(request, response);
				} else{
					chain.doFilter(request, response);
					}
			}
		}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}
}
